﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;
using NPOI.XWPF.UserModel;
using WebUpload.Web;

namespace FillWordDataByTemplate.NpoiHelper
{
    /// <summary>
    /// 
    /// </summary>
    public class NpoiDocxExport
    {

        #region test

        private static void test()
        {
            List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();

            //
            Dictionary<string, string> dict = new Dictionary<string, string>();
            dict["${电话}$"] = "13423433034";
            dict["${罚款}$"] = "99.88";
            dict["${交钱}$"] = "200.00";
            dict["${totalAmt}$"] = "300.00";

            list.Add(dict);

            //
            string filePath = @"D:\Studio\tzx-codes\用NPOI从Excel取数读Word模板生成多Word文件\FillWordDataByTemplate\_files_\这是模板2.docx";

            //
            NpoiDocxExport export = new NpoiDocxExport();
            //export.ReplaceDict = dict;
            export.ReplaceDictList = list;
            export.TemplateDocxFilePath = filePath;
            string message;
            bool ok = export.Export(out message);
            if (ok)
            {
                Process.Start(export.GetNewFolderPath());
            }
            else
            {
                MessageBox.Show("失败:" + message);
            }
        }
        #endregion

        #region public

        /// <summary>
        /// 替代清单字典
        /// </summary>
        [Obsolete("请使用列表",true)]
        public IDictionary<string, string> ReplaceDict
        {
            get
            {
                if (_replaceDict == null)
                {
                    _replaceDict = new Dictionary<string, string>();
                }
                return _replaceDict;
            }
            set { _replaceDict = value; }
        }
        private IDictionary<string, string> _replaceDict = null;

        /// <summary>
        /// 替代清单字典
        /// </summary>
        public List<Dictionary<string, string>> ReplaceDictList
        {
            get
            {
                if (_replaceDictList == null)
                {
                    _replaceDictList=new List<Dictionary<string, string>>();
                }
                return _replaceDictList;
            }
            set { _replaceDictList = value; }
        }
        private List<Dictionary<string, string>> _replaceDictList;

        /// <summary>
        /// 模板文件路径
        /// </summary>
        public string TemplateDocxFilePath
        {
            get { return _templateDocxFilePath; }
            set { _templateDocxFilePath = value; }
        }
        private string _templateDocxFilePath = null;

        /// <summary>
        /// 导出到子文件夹名(默认日期时间字符串)
        /// </summary>
        public string NewFolderName
        {
            get
            {
                if (_newFolderName == null)
                {
                    _newFolderName = DateTime.Now.ToString("yyyyMMdd_HHmmss");
                }
                return _newFolderName;
            }
            set
            {
                string v = string.Format("{0}", value).Replace("\\","_").Replace("/","_");
                _newFolderName = v;
            }
        }
        private string _newFolderName = null;

        ///// <summary>
        ///// 导出文件名所在Key
        ///// </summary>
        //public string NewDocxNameKey
        //{
        //    get { return _newDocxNameKey; }
        //    set { _newDocxNameKey = value; }
        //}
        //private string _newDocxNameKey = null;

        /// <summary>
        /// 获取本次导出对象,完整新文件夹路径
        /// </summary>
        /// <returns></returns>
        private string GetNewFolderPath()
        {
            string path1 = string.Format("{0}",Path.GetDirectoryName(TemplateDocxFilePath));
            string path2 = NewFolderName;
            return Path.Combine(path1, path2);
        }

        /// <summary>
        /// 获取保存新文件的完整路径名称
        /// </summary>
        /// <param name="index"></param>
        /// <param name="count"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        private string GetNewDocxFullPath(int index, int count,string name)
        {
            //
            string num = string.Empty;
            int len = (count <= 99) ? 2 : count.ToString().Length;
            num = index.ToString().PadLeft(len, '0') + "_";

            //
            string templatePath = Path.GetDirectoryName(TemplateDocxFilePath);
            if (string.IsNullOrEmpty(templatePath))
            {
                templatePath = "C:\\";
            }
            string fileNew = string.Format("{0}\\{1}\\{2}{3}.docx",
                templatePath.TrimEnd('\\'),
                NewFolderName,
                num,
                name
                );
            return fileNew;
        }

        /// <summary>
        /// 导出
        /// </summary>
        public bool Export(out string message)
        {
            message = null;
            if (string.IsNullOrEmpty(TemplateDocxFilePath))
            {
                message = "模板文件路径为空";
                return false;
            }
            if (!File.Exists(TemplateDocxFilePath))
            {
                message = "模板文件不存在";
                return false;
            }

            //保存位置
            string savePath = GetNewFolderPath();
            if (!Directory.Exists(savePath))
            {
                Directory.CreateDirectory(savePath);
            }

            //模板
            using (Stream fs_template = new FileStream(TemplateDocxFilePath, FileMode.Open, FileAccess.Read))
            {
                XWPFDocument doc = new XWPFDocument(fs_template);

                int count = ReplaceDictList.Count;

                //foreach (Dictionary<string, string> dict in ReplaceDictList)
                for (int i = 0; i < count; i++)
                {
                    Dictionary<string, string> dict = ReplaceDictList[i];

                    //替换段落里面的变量  
                    //Replace_Paragraph(doc, ReplaceDict);
                    Replace_Paragraph(doc, dict);

                    //替换表格里面的变量  
                    //Replace_Table(doc, ReplaceDict);
                    Replace_Table(doc, dict);

                    //string name = dict.ContainsKey(NewDocxNameKey) ? dict[NewDocxNameKey] : "";
                    string fileNew = GetNewDocxFullPath(i + 1, count, "");
                    using (Stream fs_newfile = new FileStream(fileNew, FileMode.Create, FileAccess.Write))
                    {
                        doc.Write(fs_newfile);
                        fs_newfile.Close(); //关
                    } //using
                }

                fs_template.Close();//关
            }//using

            //返回
            //_exportNewFillPathName = fileNew;
            return true;
        }

        #endregion

        #region private Replace Word

        /// <summary>
        /// 替换段落里面的变量</summary>
        /// <param name="doc">要替换的文档</param>
        /// <param name="params3">参数</param>
        private void Replace_Paragraph(XWPFDocument doc, Dictionary<string, string> params3)
        {
            IEnumerator<XWPFParagraph> iterator = doc.GetParagraphsEnumerator();
            XWPFParagraph para;
            while (iterator.MoveNext())
            {
                para = iterator.Current;
                Replace_Paragraph(para, params3);
            }
        }

        /// <summary>
        /// 替换表格里面的变量</summary>
        /// <param name="doc">要替换的文档</param>
        /// <param name="params4">参数</param>
        private void Replace_Table(XWPFDocument doc, Dictionary<string, string> params4)
        {
            IEnumerator<XWPFTable> iterator = doc.GetTablesEnumerator();
            XWPFTable table;
            IList<XWPFTableRow> rows;
            IList<XWPFTableCell> cells;
            IList<XWPFParagraph> paras;
            while (iterator.MoveNext())
            {
                table = iterator.Current;
                rows = table.Rows;
                foreach (XWPFTableRow row in rows)
                {
                    cells = row.GetTableCells();
                    foreach (XWPFTableCell cell in cells)
                    {
                        paras = cell.Paragraphs;
                        foreach (XWPFParagraph para in paras)
                        {
                            Replace_Paragraph(para, params4);
                        }//foreach paragraph
                    }//foreach cell
                }//foreach row
            }//while
        }

        /// <summary>
        /// 替换段落里面的变量</summary>
        /// <param name="para">要替换的段落</param>
        /// <param name="params5">参数</param>
        private void Replace_Paragraph(XWPFParagraph para, Dictionary<string, string> params5)
        {
            foreach (KeyValuePair<string, string> kv in params5)
            {
                string find = kv.Key;
                string replace = kv.Value;

                //LogFile.Me.LogText("find=", find, "replace=", replace);

                if (para.Text.Contains(find))
                {
                    para.ReplaceText(find, replace); //关键操作
                }
            }

            //foreach (string key in params5.Keys)
            //{
            //    if (para.Text.Contains(key))
            //    {
            //        para.ReplaceText(key, params5[key]);
            //    }
            //}

        }

        #endregion

    }
}
